﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace fes
{
    // Intraday Momentum Index
    // http://www.mbank.pl/indywidualny/inwestycje/emakler/encyklopedia/WSKAZNIKI/mfi.html
    // http://www.csidata.com/studies/Intraday_Momentum_Index_(IMI).html
    class IMI : Indicator, IIndicator
    {
        private int n = 0;
        private List<double> openPrices;
        private List<double> closePrices;
        private double currentValue = -1;

        public IMI(Dictionary<String, Object> parameters) : base("IMI")
        {
            base.setInidicatorParams(parameters);
            n = (int) parameters["n"] + 1;
            openPrices = new List<double>();
            closePrices = new List<double>();
        }

        public void setParameters(Dictionary<String, Object> parameters)
        {

            base.setInidicatorParams(parameters);
            n = (int)parameters["n"] + 1;
        }

        public override void pushNextDayData(double open, double high, double low, double close, int vol)
        {
            openPrices.Add(open);
            closePrices.Add(close);
            if (closePrices.Count > n)
            {
                closePrices.RemoveAt(0);
                openPrices.RemoveAt(0);
            }
            calculateIMI();
        }

        public override double getValue()
        {
            return currentValue;
        }

        private void calculateIMI()
        {
            int cnt = 0;
            double upSum = 0;
            double downSum = 0;
            double intradayMomentumIndex = 0; //calculated indicator

            if (closePrices.Count == n)
            {
                cnt = closePrices.Count;
                for (int i = 0; i < cnt; i++)
                {
                    if (closePrices[i] > openPrices[i])
                    {
                        upSum = upSum + (closePrices[i] - openPrices[i]);
                    }
                    else
                    {
                        downSum = downSum + (openPrices[i] - closePrices[i]);
                    }
                }
                if (upSum + downSum > 0)
                {
                    intradayMomentumIndex = 100 * (upSum / (upSum + downSum));
                }
                else
                {
                    intradayMomentumIndex = 0;
                }
                currentValue = intradayMomentumIndex;
            }
            else
            {
                currentValue = -1;
            }
        }
    }
}
